/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import models.Course;
import models.User;
import org.hibernate.Session;
import service.CourseDao;
import service.HibernateUtil;
import service.UserDao;

/**
 *
 * @author Aster
 */
public class StudentController extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        boolean student = false;
        long userID = 0;
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals("status")) {
                if (cookie.getValue().length() > 0) {
                    student = true;
                } 
            }else if (cookie.getName().equals("userID")) {
                userID = Long.parseLong(cookie.getValue());
            }
        }
        if (student == true) {
            HttpSession session = request.getSession(true);
            HibernateUtil HU = new HibernateUtil();
            Session sessie = HU.openSession();

            //stuk om de aangewezen cursussen van docent op te halen
            try {
                UserDao ud = new UserDao(sessie);
                User user = ud.get(userID);//dit moet dynamisch worden
                if (user.getCourses() != null) {
                    session.setAttribute("courses", user.getCourses());
                    session.setAttribute("theUser", user);
                }
            } catch (Exception ex) {
                System.out.println(ex);
            }
            forward(request, response);
        } else {
            response.sendRedirect("/");
        }
    }

    private void forward(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //request.setAttribute("pageTitle", titel);

        String address = "/student.jsp";
        RequestDispatcher dispatcher = request.getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }
}
